<template>
  <!-- 设计图纸管理 -->
  <base-breadcrumb class="allPlan" :breadcrumb="!isAudit">
    <a-spin :spinning="loading">
      <a-row :gutter="24">
        <a-col :span="6" style="border-right: 1px solid #d9d9d9">
          <a-card :bordered="false">
            <title-name title="分类"></title-name>
            <tree-search
              ref="treeSearch"
              :showButton="editModel != 0"
              :replaceFields="{ children: 'children', title: 'groupName', key: 'id' }"
              :id="id"
              :isReference="editModel != 0"
              :api="api"
              emptyDescription="暂无数据"
              :requestArgs="{ projectStandardId: id, year: year }"
              isAll
              @loader="loader"
              @reference="visibleTreeModal = true"
              :isDelete="true"
              :addDisable="loading"
              :selectedKeys.sync="selectedKeys"
              :selectOptions.sync="selectOptions"
            />
          </a-card>
        </a-col>
        <a-col :span="18">
          <searchData :searchData="searchArr" @search="search"></searchData>
          <a-card>
            <title-name title="规范清单"></title-name>
            <!-- 表格 -->
            <b-table :page-keys="['pageNum', 'pageSize', 'total']" ref="table" :columns="columns" :request="loadData"
                     :selectConfig="{
                          use: editModel == 0, //是否使用，传false不会显示选择栏
                          type: 'checkbox', //checkbox或radio，多选或者单选
                          rowKey: 'id'
                      }"
                     :rowSelectionConfig="rowSelectionConfig"
            >
              <!-- 新增 -->{{ selectOptions }}
              <!-- <a-button
                v-if="editModel != 0"
                slot="prefix"
                icon="plus"
                type="primary"
                :disabled="
                  selectedKeys.length == 0 || selectOptions.hasChildren || atlasStandardNumberSelect.length == 0
                "
                @click="
                  handleManage('2')
                  isUsed = 1
                "
                >引用</a-button
              > -->
              <a-button
                v-if="editModel != 0"
                slot="prefix"
                icon="plus"
                type="primary"
                :disabled="selectedKeys.length == 0 || selectOptions.hasChildren || atlasStandardNumberSelect.length == 0"
                @click="choiceSpecific()
                "
                >选择规范清单</a-button
              >
              <a-button
                v-if="editModel != 0"
                slot="prefix"
                icon="plus"
                type="primary"
                :disabled="selectedKeys.length == 0 || selectOptions.hasChildren"
                @click="
                  handleManage('2')
                  isUsed = 0
                "
                >新增</a-button
              >
              <a-button
                      v-if="editModel == 0"
                      slot="prefix"
                      type="primary"
                      :disabled="selectedRowKeys.length == 0"
                      @click="exportExcle('1')"
              >导出选中</a-button
              >
              <a-button
                      v-if="editModel == 0"
                      slot="prefix"
                      type="primary"
                      @click="exportExcle('2')"
                >导出全部</a-button
              >
              <template slot="source" slot-scope="text">
                {{text ? text : '引用'}}
              </template>
              <template slot="operation" slot-scope="text, record">
                <MoreButton>
                <a @click="handleManage('0', record)">查看</a>
                <!-- 编辑 -->
                <span v-if="editModel != 0">
                  <a @click="handleManage('1', record)">编辑</a>
                </span>
                <!-- 作废 -->
<!--                <span v-if="record.isUsed == 1 && editModel != 0">-->
<!--                  <a-divider type="vertical" />-->
<!--                  <a-popconfirm title="确定要作废?" @confirm="() => handleRemove(record, 2)">-->
<!--                    <a>作废</a>-->
<!--                  </a-popconfirm>-->
<!--                </span>-->
<!--                &lt;!&ndash; 过期 &ndash;&gt;-->
<!--                <span v-if="record.isUsed == 1 && editModel != 0">-->
<!--                  <a-divider type="vertical" />-->
<!--                  <a-popconfirm title="确定要过期?" @confirm="() => handleRemove(record, 1)">-->
<!--                    <a>过期</a>-->
<!--                  </a-popconfirm>-->
<!--                </span>-->
                <!-- 删除 -->
                <span v-if="editModel != 0">
                  <a-popconfirm title="确定要删除?" @confirm="() => handleRemove(record, 0)">
                    <a>删除</a>
                  </a-popconfirm>
                </span>
                </MoreButton>
              </template>
            </b-table>
          </a-card>
        </a-col>
      </a-row>
      <div v-if="!isConsultation" class="btn_box page-btn-right-top">
        <a-button @click="handleActiveClose">关闭</a-button>
      </div>
    </a-spin>
    <DialogForm
      ref="dialogForm"
      :visible.sync="visible"
      :edit-model="editModelDialog"
      :form="form"
      :header-title="editModelDialog == 'V' ? '查看规范清单' : editModelDialog == 2 ? '新增规范清单' : '编辑规范清单'"
      :width="700"
      :isEmit="false"
      :rules="rules"
      :form-list="formList"
      :forms.sync="forms"
      @confirm="submitForm"
      :clearForm="true"
      :styles="{ width: '450px' }"
    />
    <tree-modal
      ref="treeModal"
      :requestArgs="{ year: year, projectId: projectId }"
      :visible.sync="visibleTreeModal"
      :outCheckedKeys="outCheckedKeys"
      @confirm="confirm"
    />
    <ChoiceSpecific  :visibleSpecific.sync="visibleSpecific" :queryParam="queryParam" @hideVisible="hideVisible"/>
  </base-breadcrumb>
</template>
<script>
import { STable } from '@/components' // 表格
import DialogForm from '@/components/DialogForm' // 弹窗
import TreeSearch from '../TreeSearch' // 树
import ChoiceSpecific from './choiceSpecific' // 选择项目规范
import {
  addProjectStandard,
  getProjectStandardTreeList,
  addProjectTree,
  updateProjectTree,
  delProjectTree,
  getTableList,
  addTable,
  updateTable,
  delTable,
  expireTable,
  invalidTable,
  getBasicsTableListSelect,
  addQuote,
  getProjectStandardDetails,
  getProjectNodeTree
} from '@/api/technical/specificationList'
import { technicalProjectStandardDetailedListExport, updateTechnicalProjectStandardDetailed } from "@/api/technology"
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import treeModal from './treeModal.vue' // 表单弹窗
import { columns } from './model'
const searchArr = [
  {
    name: '图集/标准号',
    value: 'atlasStandardNumber',
    type: 'input'
  },
  {
    name: '图集名称',
    value: 'atlasName',
    type: 'input'
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    STable,
    TreeSearch,
    DialogForm,
    treeModal,
    ChoiceSpecific
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      isInit: true,
      selectedKeys: [],
      selectOptions: {},
      loading: false,
      visible: false, // 弹窗控件
      visibleTreeModal: false,
      visibleSpecific:false,
      isUsed: 0, //是否引用
      editModelDialog: '0',
      year: new Date().getFullYear() + '',
      // year: '2020',
      projectId: this.$userInfo().currentPost.id,
      api: {
        getList: getProjectStandardTreeList,
        create: addProjectTree,
        update: updateProjectTree,
        delete: delProjectTree,
        getDetails: getProjectNodeTree
      },
      form: {
        groupName: '',
        type: '',
        remark: '',
        atlasName: ''
      },
      forms: {},
      rules: {
        atlasStandardNumber: [{ required: true, message: '请输入' }],
        atlasName: [{ required: true, message: '请输入' }],
        type: [{ required: true, message: '请输入' }],
        remark: [{ required: true, message: '请输入' }]
      },
      id: '',
      outCheckedKeys: [],
      atlasStandardNumberSelect: [],
      queryParam: {},
      loadData: async parameter => {
        if (this.selectOptions.id) {
          this.queryParam.projectStandardId = this.id
          this.queryParam.isEffective = 1;
          if(!this.isInit) {
            this.queryParam.groupMenuId = this.selectedKeys.length > 0 ? this.selectOptions.id : void 0
          }

          const requestParameters = Object.assign({}, parameter, { param: this.queryParam })
          return getTableList(requestParameters).then(res => {
            if (res.code === '0') {
              return {
                code: 200,
                data: res.data.list,
                total: res.data?.total,
                currentPage: res.data?.pageNum
              }
            }
          })
        } else {
          return {
            code: 200,
            data: []
          }
        }
      },
      specificData:[],  //选择规范数据
      selectedRowKeys: []
    }
  },
  computed: {
    rowSelectionConfig(){
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
    formList() {
      return [
        {
          keyName: 'groupName',
          type: 'BaseInput',
          label: '所属分类',
          disabled: true,
          span: 24
        },
        {
          hidden: this.isUsed == 1,
          keyName: 'atlasStandardNumber',
          type: 'BaseInput',
          label: '图集/标准号',
          span: 24
        },
        {
          hidden: this.isUsed == 0,
          keyName: 'atlasStandardNumber',
          type: 'a-select',
          label: '图集/标准号',
          span: 24,
          data: this.atlasStandardNumberSelect,
          change: e => {
            console.log(e)
            let data = this.atlasStandardNumberDatas.filter(item => item.atlasStandardNumber === e)[0]
            this.forms.atlasName = data.atlasName
            this.forms.type = data.type
            this.forms.remark = data.remark
            this.forms.basicId = data.id
          }
        },
        {
          keyName: 'atlasName',
          type: 'BaseInput',
          label: '图集名称',
          disabled: this.isUsed == 1,
          span: 24
        },
        {
          keyName: 'type',
          type: 'BaseInput',
          label: '类型',
          disabled: this.isUsed == 1,
          span: 24
        },
        {
          keyName: 'remark',
          type: 'BaseTextarea',
          disabled: this.isUsed == 1,
          label: '备注',
          span: 24
        }
      ]
    }
  },
  mounted() {
    this.$route.meta.title = ['项目规范查看', '项目规范编辑', '项目规范新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.getProjectStandardDetails()
    } else {
      this.$nextTick(() => {
        this.addProjectStandardReq()
        this.init = true
      })
    }
  },
  methods: {
    onSelectChange(selectRowKeys) {
      this.selectedRowKeys = selectRowKeys
    },
    exportExcle(type) {
      if(type==='1') {
        technicalProjectStandardDetailedListExport({ids: this.selectedRowKeys, ...this.queryParam }).then(res=>{
          this.downLoadExl(res.data)
        })
      } else {
        technicalProjectStandardDetailedListExport(this.queryParam).then(res=>{
          this.downLoadExl(res.data)
        })
      }
    },
    downLoadExl(data){
      const blob = new Blob([data])
      const url = window.URL.createObjectURL(blob)
      const ele = document.createElement("a")
      ele.href = url;
      ele.target="_blank"
      ele.download = '项目规范清单.xlsx'
      document.body.appendChild(ele)
      ele.click()
      document.body.removeChild(ele)
    },
    hideVisible(){
      this.visibleSpecific = false;
      this.$refs.treeSearch?.getList().then(res => {
      this.$refs.table.refresh(true)
    })
  },
    handleRemove(record, type) {
      const api = [delTable, expireTable, invalidTable][type]
      this.$refs.table.innerLoading = true
      api({ id: record.id })
        .then(res => {
          this.$message.success(['删除', '过期', '作废'][type] + '成功!')

          this.$refs.treeSearch?.getList().then(res => {
            this.$refs.table.refresh(true)
          })
        })
        .catch(e => {
          this.$refs.table.innerLoading = false
        })
    },
    /**
     * 操作栏 type:0 新增;1 编辑
     */
    handleManage(type, record) {
      this.editModelDialog = type == '0' ? 'V' : type // 映射操作类型
      this.form = type != '2' ? this.$clone(record) : {} // 配置参数
      this.form.groupName = type == '2' ? this.selectOptions?.groupName : this.form.groupName //设置选中分类
      this.visible = true // 打开表单
    },
     /**
     * 选择规范清单
     */
    choiceSpecific(){
      this.visibleSpecific = true;
    },
    /**
     * 表格新增
     */
    submitForm(e) {
      e.projectStandardId = this.id //主表id
      e.isUsed = this.isUsed
      if(this.editModelDialog == 2) {
        e.source = '新增'
        e.groupMenuId = this.selectOptions?.id //分类id
      }
      const api = [updateTable, addTable][this.editModelDialog - 1]
      this.$refs.dialogForm.loading = true
      api(e)
        .then(res => {
          this.$refs.dialogForm.loading = false
          this.visible = false
          this.$message.success(['修改', e.isUsed == 1 ? '引用' : '新增'][this.editModelDialog - 1] + '成功')
          this.$refs.treeSearch?.getList().then(res => {
            this.$refs.table.refresh(true)
          })
        })
        .catch(res => {
          // that.$message.warning(['添加', '编辑'][that.editModel] + '失败！')
          this.$refs.dialogForm.loading = false
        })
    },
    loader() {
      this.isInit = false
      console.log(this.selectOptions)
      this.$refs.table.refresh(true)
      this.getBasicsTableListReq()
    },
    //获取引用分类清单
    getBasicsTableListReq() {
      const requestParameters = getBasicsTableListSelect({ groupMenuIds: [this.selectOptions.basicTreeId] }).then(
        res => {
          this.atlasStandardNumberDatas = this.$clone(res.data)
          this.atlasStandardNumberSelect = res.data.map(item => {
            return {
              label: item.atlasStandardNumber,
              value: item.atlasStandardNumber
            }
          })
        }
      )
    },
    //搜索
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    //提交引用
    confirm(e) {
      console.log(e)
      this.$refs.treeModal.confirmLoading = true

      addQuote({ pointIds: e, id: this.id })
        .then(res => {
          this.getProjectStandardDetails()
          this.$message.warning('引用成功!')
          this.visibleTreeModal = false
          this.$refs.treeModal.confirmLoading = false
        })
        .catch(e => {
          this.$refs.treeModal.confirmLoading = false
        })
    },
    //获取详情
    getProjectStandardDetails(openModal = false) {
      this.loading = true
      getProjectStandardDetails({ id: this.id }).then(res => {
        this.loading = false
        this.projectId = res.data.projectId
        this.outCheckedKeys = res.data.pointIds
        this.$refs.treeSearch?.getList().then(res => {
          this.$refs.table.refresh(true)
          this.visibleTreeModal = openModal
        })
      })
    },
    //新增
    async addProjectStandardReq() {
      this.loading = true
      const userInfo = this.$userInfo()
      if (userInfo.currentPost.code !== 'PD') {
        this.$message.warning('非项目部岗位不可以添加数据!')
        this.handleActiveClose()
        return
      }

      let param = {
        year: this.year,
        branchCompanyId: userInfo.currentPost.orgId,
        projectId: userInfo.currentPost.id
      }
      addProjectStandard(param)
        .then(res => {
          this.id = res.data.id

          this.getProjectStandardDetails(true)
        })
        .catch(e => {
          this.loading = false
        })
    }
  }
}
</script>
